package com.example.demo.controller;

import com.example.demo.po.FastDFSFile;
import com.example.demo.util.FastDFSClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Admin
 */
@RestController
public class myFastDFS {
    @RequestMapping("/")
    public String index() {
        return "1";
    }


    @PostMapping("upload")
    public String upload(MultipartFile file) {
        try {
            // 文件上传
            // 1. 获取文件属性
            // 1.1. 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 1.2. 文件内容
            byte[] fileBytes = file.getBytes();
            // 1.3 文件扩展名  test.jpg -> jpg
            assert originalFilename != null;
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            // 2. 创建 FastDFSFile
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, fileBytes, ext);
            // 3. 调用工具类上传
            // uploadResult 第一个只是 group 第二个值是：物理路径
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            // 预览url
            String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];

            return "上传成功 + "+url;
        } catch (Exception e) {
            return "上传失败" + e.getMessage();
        }
    }


}
